#include "dropwidget.h"
#include "ui_dropwidget.h"
#include <QDebug>
#include <QMessageBox>

DropWidget::DropWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::DropWidget)
{
    ui->setupUi(this);
    this->setWindowFlags(Qt::CustomizeWindowHint | Qt::FramelessWindowHint);
    this->setProperty("useStyleWindowManager",false);
    this->setAcceptDrops(true);
    setAutoFillBackground(true);
//    setBackgroundRole(QPalette::Window);
//    m_fileRepeatDlg=new FileRepeatDialog;
    m_licenseFilePathList.clear();
    m_licenseFileNameList.clear();

    QPalette pe;
    pe.setColor(QPalette::Text, QColor(129,129,129));
    ui->activationremindlabel->setPalette(pe);

}

DropWidget::~DropWidget()
{
//    delete m_fileRepeatDlg;
    delete ui;
}

//当用户拖动文件到窗口部件上时候，就会触发dragEnterEvent事件
void DropWidget::dragEnterEvent(QDragEnterEvent *event)
{
    //如果为文件，则支持拖放
    if (event->mimeData()->hasFormat("text/uri-list"))
        event->acceptProposedAction();
}

//当用户放下这个文件后，就会触发dropEvent事件
void DropWidget::dropEvent(QDropEvent *event)
{
    //注意：这里如果有多文件存在，意思是用户一下子拖动了多个文件，而不是拖动一个目录
    //如果想读取整个目录，则在不同的操作平台下，自己编写函数实现读取整个目录文件名
    QList<QUrl> urls = event->mimeData()->urls();
    if(urls.isEmpty())
        return;

    //往文本框中追加文件名
    foreach(QUrl url, urls) {
        QString path = url.toLocalFile();
        QFileInfo fileInfo(path);
        if(fileInfo.isFile() && fileInfo.exists())
        {
            filterLicenseFiles(fileInfo);
        }
    }
}

void DropWidget::on_pushButton_clicked()
{
    QFileDialog fileDlg;
    fileDlg.setOption(QFileDialog::DontUseNativeDialog,false);
    fileDlg.setFileMode(QFileDialog::ExistingFiles);
    fileDlg.setViewMode(QFileDialog::Detail);
    fileDlg.setDirectory(QDir::homePath());
    //过滤kyinfo和LICENSE文件
//    fileDlg.setFilter(QDir::AllDirs | QDir::Files | QDir::NoDotAndDotDot);
    fileDlg.setNameFilter("*kyinfo* *LICENSE*");

    //左侧导航栏添加u盘
    urls.clear();
    urls=fileDlg.sidebarUrls();

    int sidebarNum = 8;//最大添加U盘数，可以自己定义
    QString home = QDir::homePath().section("/", -1, -1);
    QString mnt = "/media/" + home + "/";
    QDir mntDir(mnt);
    mntDir.setFilter(QDir::Dirs | QDir::NoDotAndDotDot);
    QFileInfoList filist = mntDir.entryInfoList();
    QList<QUrl> mntUrls;
    for (int i = 0; i < sidebarNum && i < filist.size(); ++i) {
        QFileInfo fi = filist.at(i);
        //华为990、9a0需要屏蔽最小系统挂载的目录
        if (fi.fileName() == "2691-6AB8")
            continue;
        mntUrls << QUrl("file://" + fi.filePath());
    }
    fileDlg.setSidebarUrls(urls + mntUrls);
    fileDlg.update();
    //监控U盘挂载
    QFileSystemWatcher fsw(&fileDlg);
    fsw.addPath("/media/" + home + "/");
    connect(&fsw, &QFileSystemWatcher::directoryChanged, &fileDlg,
            [=, &sidebarNum, &mntUrls, &fileDlg](const QString path) {
        QDir wmntDir(path);
        wmntDir.setFilter(QDir::Dirs | QDir::NoDotAndDotDot);
        QFileInfoList wfilist = wmntDir.entryInfoList();
        mntUrls.clear();
        for (int i = 0; i < sidebarNum && i < wfilist.size(); ++i) {
            QFileInfo fi = wfilist.at(i);
            //华为990、9a0需要屏蔽最小系统挂载的目录
            if (fi.fileName() == "2691-6AB8")
                continue;
            mntUrls << QUrl("file://" + fi.filePath());
        }
        fileDlg.setSidebarUrls(urls + mntUrls);
        fileDlg.update();
    });
    //还原侧边栏
    connect(&fileDlg, &QFileDialog::finished, &fileDlg, [=, &fileDlg]() {
        fileDlg.setSidebarUrls(urls);
    });

    QStringList filePaths;
    if((fileDlg.exec()))
        filePaths=fileDlg.selectedFiles();
    foreach(QString path, filePaths) {
        QFileInfo fileInfo(path);
        if(fileInfo.isFile() && fileInfo.exists())
        {
            filterLicenseFiles(fileInfo);
        }
    }

}

void DropWidget::cleanData()
{
    m_licenseFilePathList.clear();
    m_licenseFileNameList.clear();
}

QStringList DropWidget::getLicenseFilePathList()
{
    return m_licenseFilePathList;
}

void DropWidget::deleteFile(QString filename)
{
    int indf = m_licenseFileNameList.indexOf(filename);
    m_licenseFilePathList.removeAt(indf);
    m_licenseFileNameList.removeAt(indf);
    qDebug()<<"m_licenseFilePathList:"<<m_licenseFilePathList;
    qDebug()<<"m_licenseFileNameList:"<<m_licenseFileNameList;

}

void DropWidget::paintEvent(QPaintEvent *e)
{
    QPainter painter(this);
    QPen pen;
    pen.setStyle(Qt::DashLine);
    pen.setColor(QColor(209,209,209));
    painter.setPen(pen);
    painter.drawRect(0,0,width()-1,height()-1);
}

void DropWidget::filterLicenseFiles(QFileInfo fileInfo)
{
    QStringList formatList=QStringList()<<"zip"<<"gz"<<"bz2";
    if(formatList.contains(fileInfo.suffix()) || //过滤压缩文件
            (fileInfo.fileName().contains("kyinfo", Qt::CaseInsensitive) && fileInfo.fileName().contains("LICENSE", Qt::CaseInsensitive)) || //过滤同时包含kyinfo和LICENSE字段名的文件
            (!fileInfo.fileName().contains("kyinfo", Qt::CaseInsensitive) && !fileInfo.fileName().contains("LICENSE", Qt::CaseInsensitive))//过滤非kyinfo与LICENSE的文件
            )
    {
        QMessageBox box(QMessageBox::Information, NULL, QString(tr("Invalid filename: ")+fileInfo.fileName()+tr(", please import kyinfo and LICENSE text files.")),QMessageBox::NoButton,this);
        QPushButton *closeButton = box.addButton(tr("Close"), QMessageBox::AcceptRole);
        box.setDefaultButton(closeButton);
        box.exec();

    }
    else if(fileInfo.fileName().contains("kyinfo", Qt::CaseInsensitive) || fileInfo.fileName().contains("LICENSE", Qt::CaseInsensitive))//模糊匹配kyinfo与LICENSE字段名
    {
        bool isRepeat=false;
        m_similarFileName.clear();
        for(int index=0; index<m_licenseFileNameList.size(); index++)
        {
            QString name=m_licenseFileNameList.at(index);
            if((name.contains("LICENSE") && fileInfo.fileName().contains("LICENSE")) ||
                    (name.contains("kyinfo") && fileInfo.fileName().contains("kyinfo")))//过滤子文件名
            {
                m_similarFileName=name;
                isRepeat=true;
                break;
            }
        }
        if(!isRepeat)
        {
            m_licenseFilePathList.append(fileInfo.filePath());
            m_licenseFileNameList.append(fileInfo.fileName());
            emit addLicenseFile(m_licenseFileNameList);
        }
        else
        {
            //文件重复
            m_repeatFilePath.clear();
            m_repeatFilePath=fileInfo.filePath();

            QMessageBox box(this);
            box.setIcon(QMessageBox::Warning);
            box.setStandardButtons(QMessageBox::Cancel|QMessageBox::Ok);
            box.setText(QString(tr("Existing similar filename: ")+fileInfo.fileName()+tr(", whether to overwrite?")));
            int ret=box.exec();
            if(ret==QMessageBox::Ok)
            {
                QFileInfo fileInfo(m_repeatFilePath);
                m_licenseFilePathList.replace(m_licenseFileNameList.indexOf(m_similarFileName),fileInfo.filePath());
                m_licenseFileNameList.replace(m_licenseFileNameList.indexOf(m_similarFileName),fileInfo.fileName());
                emit addLicenseFile(m_licenseFileNameList);
            }
        }
    }
    else //未知错误
    {
        QMessageBox box(QMessageBox::Warning, NULL, QString(tr("Please import kyinfo and LICENSE text files.")),QMessageBox::NoButton,this);
        QPushButton *closeButton = box.addButton(tr("Close"), QMessageBox::AcceptRole);
        box.setDefaultButton(closeButton);
        box.exec();
    }
}
